package com.example.laserharp1;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.util.Log;

public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
    private WifiP2pManager mManager;
    private WifiP2pManager.Channel mChannel;
    private ConnectionPage mActivity;

    public WiFiDirectBroadcastReceiver(WifiP2pManager mManager, WifiP2pManager.Channel mChannel, ConnectionPage mActivity)
    {
        this.mManager = mManager;
        this.mChannel = mChannel;
        this.mActivity = mActivity;
    }

    @SuppressLint("LongLogTag")
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        Log.e("WiFiDirectBroadcastReceiver", "action="+action);
        //当Wifi状态发生改变的时候调用， 也可能是Wifi开启和关闭
        if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
        }

        else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)){
            if (mManager!=null)
            {
                mManager.requestPeers(mChannel, mActivity.peerListListener);
            }
            //当WifiP2p连接状态改变的时候回调，注意需要分清是关闭连接还是开启连接
        }

        else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
            Log.e("WiFiDirectBroadcastReceiver", "action="+"WIFI_P2P_CONNECTION_CHANGED_ACTION");
            if (mManager == null){
                return;
            }
            NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
            Log.e("WiFiDirectBroadcastReceiver", "networkInfo.isConnected()="+networkInfo.isConnected());
            if (networkInfo.isConnected())
            {
                mManager.requestConnectionInfo(mChannel, mActivity.connectionInfoListener);
            }else{
                mActivity.connectionStatus.setText("connection status:  device disconnected");
            }
            //当Wifi本身信息发生改变的时候调用，可以获取到自身Device的信息
        }
    }
}
